// pages/member/rankingListSecond/rankingListSecond.js
var app = getApp();
Page({

  /**
	 * 页面的初始数据
	 */
  data: {
    codes: [],
    value: '',
    show: false,
    show1: false,
    username: '',
    uid: '',
    showPayConfirm: false,
    paymentAmount: ''
  },

  /**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function(options) {
    this.getData();
  },

  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function() {},

  /**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function() {},

  /**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function() {},

  /**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function() {},

  /**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
  onPullDownRefresh: function() {},

  /**
	 * 页面上拉触底事件的处理函数
	 */
  onReachBottom: function() {},

  /**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function() {},

  // 获取数据
  getData() {
    let urlStr = app.getNetAddresss('plugin.team-dividend.api.index.getCode');
    app._getNetWork({
      url: urlStr,
      success: (res) => {
        let resData = res.data;
        if (resData.result === 1) {
          this.setData({
            codes: resData.data.code
          });
        } else {
          wx.showToast({
            title: resData.msg,
            icon: 'none'
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  copyCode(event) { //复制
    let text = event.currentTarget.dataset.text;
    wx.setClipboardData({
      data: text,
      success: function (res) {
        wx.getClipboardData({
          //这个api是把拿到的数据放到电脑系统中的
          success: function (res) {
            wx.showToast({
              title: '复制成功',
              icon: 'success',
              duration: 2000
            });
          }
        });
      }
    });
  },

  // 返回
  goBack() {
    wx.navigateBack({
      delta: 1
    });
  },
  // 跳转到使用记录
  codeHistory() {
    wx.navigateTo({
      url: '/packageB/member/income/codeHistory/codeHistory'

    });
  },
  // 验证对话
  openDialog() {
    this.setData({
      show1: true
    });
  },
  // 取消
  onClose() {
    this.setData({
      show1: false
    });
  },
  // 验证激活码
  getUserInfo() {
    if (this.data.username == '') {
      wx.showToast({
        title: '请输入激活码',
        icon: 'none'
      });
      return false;
    }
    if(this.data.uid == '') {
      wx.showToast({
        title: '请输入用户id',
        icon: 'none'
      });
      return false;
    }

    console.log(this.data.username, this.data.uid);
    
    // 先调用检查是否需要支付的接口
    let checkUrl = app.getNetAddresss('plugin.team-dividend.api.index.check-payment-required');
    app._postNetWork({
      url: checkUrl,
      data: {
        code: this.data.username,
        uid: this.data.uid
      },
      success: (res) => {
        if (res.data.result === 1) {
          const data = res.data.data;
          // 如果不需要支付，走原来的逻辑
          if (!data.need_pay) {
            this.useCodeDirectly();
          } else {
            // 如果需要支付，弹窗让用户确认
            this.setData({
              showPayConfirm: true,
              paymentAmount: data.amount
            });
          }
        } else {
          wx.showToast({
            title: res.data.msg || '获取支付信息失败',
            icon: 'none'
          });
        }
      },
      fail: function(res) {
        console.log(res);
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },
  
  // 直接使用激活码（不需要支付的情况）
  useCodeDirectly() {
    let urlStr = app.getNetAddresss('plugin.team-dividend.api.index.useCode');
    urlStr += '&code=' + this.data.username + '&uid=' + this.data.uid;
    app._getNetWork({
      url: urlStr,
      success: (res) => {
        app.tips(res.data.msg);
        if (res.data.result === 1) {
          this.getData();
          this.setData({
            show1: false
          });
        } else {
          this.setData({
            show1: false
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  
  // 去支付
  goToPay() {
    this.setData({
      showPayConfirm: false
    });
    
    // 调用创建支付的接口
    let createUrl = app.getNetAddresss('plugin.team-dividend.api.create');
    app._postNetWork({
      url: createUrl,
      data: {
        uid: this.data.uid,
        code: this.data.username,
        price: this.data.paymentAmount
      },
      success: (res) => {
        app.tips(res.data.msg);
        if (res.data.result === 1) {
          // 获取order_ids
          const orderIds = res.data.data.order_ids;
          // 使用order_ids调用支付接口获取支付参数
          wx.navigateTo({
            url: `/packageD/buy/orderPay/orderPay?order_id=${orderIds}`,
          });
          // this.getPaymentParams(orderIds);
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  
  // 获取支付参数
  getPaymentParams(orderIds) {
    let payUrl = app.getNetAddresss('order.merge-pay');
    app._postNetWork({
      url: payUrl,
      data: {
        order_ids: orderIds
      },
      success: (res) => {
        if (res.data.result === 1) {
          // 获取支付参数并调用微信支付
          const payParams = res.data.data.pay_params;
          this.WXPay(payParams);
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  
  // 调用微信支付API
  WXPay(payParams) {
    let that = this;
    wx.requestPayment({
      timeStamp: payParams.timeStamp,
      nonceStr: payParams.nonceStr,
      package: payParams.package,
      signType: payParams.signType ? payParams.signType : 'MD5',
      paySign: payParams.paySign,
      success: function(res) {
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000
        });
        // 支付成功后刷新数据
        that.getData();
        that.setData({
          show1: false
        });
      },
      fail: function(res) {
        wx.showToast({
          title: '支付失败，请稍后重试',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },
  
  // 关闭支付确认弹窗
  closePayConfirm() {
    this.setData({
      showPayConfirm: false
    });
  }
});
